<?php

namespace app\admin\model;

use think\Exception;
use think\Model;

class Menu extends Model
{
    public function tree()
    {
        //这个表示那拿到的数据库里面的内容
        $menu = $this->order('sort', 'asc')->select();
        return $this->getTree($menu);
    }

    /**
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 二级菜单
     */
    public function getChild()
    {
        $menus = $this::where('pid', '=', 0)->select();
        if ($menus) {
            foreach ($menus as $key => $menu) {
                $childs = $this::where('pid', '=', $menu->id)->select();
                $menus[$key]['child'] = $childs;
            }
        } else {
            throw new Exception("查询menu菜单失败!");
        }
        return $menus;
    }

    //无限极递归
    public function getTree($data, $pid = 0, $level = 0)
    {
        static $arr = array();
        foreach ($data as $key => $value) {
            if ($value['pid'] == $pid) {
                $value['level'] = $level;     //用来作为在模版进行层级的区分
                $arr[] = $value;            //把内容存进去
                $this->getTree($data, $value['id'], $level + 1);    //回调进行无限递归
            }
        }
        return $arr;
    }

}
